<?php
namespace App\Console\Commands;

use App\Models\SwtTradeAccount;
use App\Models\SwtTradeAccountLog;
use App\Models\SwtTradeAddress;
use App\Models\SwtTradeOrder;
use App\Services\TronService;
use Illuminate\Console\Command;

class CheckTronTransactions extends Command
{
    protected $signature = 'tron:check-transactions';

    protected $description = 'Check for new transactions for a Tron address';

    protected $tronService;
    public function __construct(TronService $tronService)
    {
        parent::__construct();
        $this->tronService = $tronService;
    }

    public function handle()
    {
        $list = SwtTradeAddress::where('coin','Tron') -> where('chain_name','USDT') -> where('type',1) -> get();

        if(!$list) {
            return;
        }

        $list = $list -> toArray();

        foreach($list as $v) {
            $transactions = $this->tronService->getTransactions($v['address']);

            if (empty($transactions['token_transfers'])) {
                continue;
            }

            foreach ($transactions['token_transfers'] as $transaction) {
                $has = SwtTradeOrder::where('transaction_id', $transaction['transaction_id']) -> exists();

                if($has) {
                   continue;
                }

                $num = bcdiv($transaction['quant'] , pow(10, $transaction['tokenInfo']['tokenDecimal']), 5);

                $data = [
                    "transaction_id"    => $transaction['transaction_id'],
                    "address_id"        => $v['id'],
                    "user_id"           => $v['user_id'],
                    "coin_id"           => 252,
                    "network_id"        => 581,
                    "to_address"        => $v['address'],
                    "from_address"      => $transaction['from_address'],
                    "type"              => 0,
                    "num"               => $num,
                    "status"            => $transaction['finalResult'] == "SUCCESS" ? 1 : 0,
                ];

                $order_info = SwtTradeOrder::create($data);

                if($order_info) {
                    SwtTradeAddress::where('id', $v['id']) -> increment('total', $num);

                    SwtTradeAccountLog::create([
                        "address_id"    => $v['id'],
                        "user_id"       =>  $v['user_id'],
                        "source_type"   => 3,
                        "source_id"     => $order_info->id,
                        "text"          => "充币" . $num. ' USDT',
                        "change_type"   => 0,
                        'change_amount' => $num
                    ]);
                }
            }
        }
    }
}
